/**
 * Created by oureda on 5/29/16.
 */
var path = require("path");
var fs = require("fs");
var db = require("../models/index");
var msgWrapper = require("../helpers/msgWrapper");
var SMS = require('../helpers/sms.js');
var Session = require('../instances/session');
var Sign = require('../instances/sign');
var Data = db.models.Data;
var User = db.models.User;

module.exports = (router) => {
    router.post('/register', (req, res) => {
        var body = req.body;
        req.checkBody('phone').notEmpty();
        req.checkBody('pwd').notEmpty();
        req.checkBody('verification').notEmpty();
        var errors = req.validationErrors();
        if (errors) {
            res.send(msgWrapper(errors, true));
            return;
        }
        return SMS
            .verify(body.phone, body.verification)
            .then((response) => {
                var data = JSON.parse(response.text);
                if(data.status !== 200) {
                    res.send(msgWrapper(response.text,true,-1));
                    return;
                }
                //User.findOne
                User.create({
                    phone: body.phone,
                    pwd: body.pwd
                }).then((user) => {
                    res.send(msgWrapper('ok'));
                }).catch((err) => {
                    console.log(err.stack);
                    res.send(msgWrapper('user exist'));
                });
            }).catch((err) => {
                console.log(err);
            });
    });

    router.post('/login', (req, res) => {
        var body = req.body;
        req.checkBody('phone').notEmpty();
        req.checkBody('pwd').notEmpty();
        var errors = req.validationErrors();
        if (errors) {
            res.send(msgWrapper(errors, true));
            return;
        }
        return User.findOne({
            where: {
                phone: body.phone,
                pwd: body.pwd
            }
        }).then((user) => {
            if (typeof(user) === 'undefined' || user == null) {
                res.send(msgWrapper('No Such User Or Password Error', true));
                return;
            }
            var token = Sign.generatorToken(user.phone, user.pwd);
            Session.setx(token, 60 * 60, user);
            res.send(msgWrapper({token:token}));
        });
    });

};